package com.blb.gatewayservice.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/**
 * 登录验证过滤器
 */
//@Component
public class LoginAuthenticationFilter implements GlobalFilter, Ordered {

    //请求过滤
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得请求头
        String auth = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        //对请求头进行验证，成功放行，否则拦截
        if("helloworld".equals(auth)){
            System.out.println("请求放行：" + request.getURI());
            return chain.filter(exchange);
        }
        //设置响应代码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //给客户端返回错误提示信息
        DataBuffer wrap = response.bufferFactory().wrap("faild".getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    //设置执行顺序，值越小执行越早
    @Override
    public int getOrder() {
        return 0;
    }
}
